//******************************************************************
//******************************************************************
//**********          ANts Peer To Peer Sources        *************
//
// ANts P2P realizes a third generation P2P net. It protects your
// privacy while you are connected and makes you not trackable, hiding
// your identity (ip) and crypting everything you are sending/receiving
// from others.

// Copyright (C) 2004  Roberto Rossi

// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


package ants.p2p.utils.addresses;

import java.net.InetAddress;

public class InetAddressRange {
  RangeMark start;
  RangeMark end;

  public InetAddressRange(String start, String end) throws Exception{
    this.start = new RangeMark(start);
    this.end = new RangeMark(end);
    if(this.start.compareTo(this.end) > 0) throw new Exception("Start address is higher than end address");
  }

  public boolean isInRange(String ip) throws Exception{
    RangeMark currentIp = new RangeMark(ip);
    if(currentIp.compareTo(this.start) >= 0 &&
      currentIp.compareTo(this.end) <= 0)
      return true;
    else
      return false;
  }
}

class RangeMark implements Comparable{
  String ip;

  public RangeMark(String ip) throws Exception{
    InetAddress.getByName(ip);
    this.ip = ip;
  }

  public int compareTo(Object o){
    if(o instanceof RangeMark){
      try{
      RangeMark other = (RangeMark)o;
      int[] thisParts = this.getTokens();
      int[] otherParts = other.getTokens();
      for(int x = 0; x < thisParts.length; x++){
        if(thisParts[x] < otherParts[x]){
          return -1;
        }else if(thisParts[x] > otherParts[x]){
          return 1;
        }
      }
      }catch(Exception e){
        e.printStackTrace();
      }
      return 0;
    }else
      return 0;
  }

  private int[] getTokens() throws Exception{
    String[] parts = this.ip.split("[.]");
    int[] intParts = new int[parts.length];
    for(int x = 0; x < parts.length; x++){
      intParts[x] = Integer.parseInt(parts[x]);
    }
    return intParts;
  }
}
